/**
 * 手势支持检测Hook
 * Story 5: Task 7 - 桌面端兼容性检测
 */

import { useState, useEffect } from 'react'

interface GestureSupportInfo {
  isTouchDevice: boolean
  supportsHaptic: boolean
  supportsPointerEvents: boolean
  isMobile: boolean
}

/**
 * 检测设备是否支持手势和触摸功能
 */
export const useGestureSupport = (): GestureSupportInfo => {
  const [support, setSupport] = useState<GestureSupportInfo>(() => {
    // 初始检测（SSR安全）
    if (typeof window === 'undefined') {
      return {
        isTouchDevice: false,
        supportsHaptic: false,
        supportsPointerEvents: false,
        isMobile: false,
      }
    }

    return detectGestureSupport()
  })

  useEffect(() => {
    // 客户端检测
    setSupport(detectGestureSupport())

    // 监听屏幕方向变化
    const handleOrientationChange = () => {
      setSupport(detectGestureSupport())
    }

    window.addEventListener('orientationchange', handleOrientationChange)
    return () => {
      window.removeEventListener('orientationchange', handleOrientationChange)
    }
  }, [])

  return support
}

/**
 * 检测手势支持
 */
function detectGestureSupport(): GestureSupportInfo {
  // 检测触摸支持
  const isTouchDevice =
    'ontouchstart' in window ||
    navigator.maxTouchPoints > 0 ||
    (navigator as any).msMaxTouchPoints > 0

  // 检测触觉反馈支持
  const supportsHaptic = 'vibrate' in navigator

  // 检测指针事件支持
  const supportsPointerEvents = 'PointerEvent' in window

  // 检测是否为移动设备（基于用户代理和屏幕尺寸）
  const isMobile =
    isTouchDevice &&
    (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      navigator.userAgent
    ) ||
      window.innerWidth < 768)

  return {
    isTouchDevice,
    supportsHaptic,
    supportsPointerEvents,
    isMobile,
  }
}

/**
 * 获取手势支持信息（非Hook版本）
 */
export const getGestureSupport = (): GestureSupportInfo => {
  if (typeof window === 'undefined') {
    return {
      isTouchDevice: false,
      supportsHaptic: false,
      supportsPointerEvents: false,
      isMobile: false,
    }
  }

  return detectGestureSupport()
}
